<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Excel多语言分组展示</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <style>
        body { font-family: "微软雅黑", Arial, sans-serif }
        .group-block { margin: 20px 0; padding:10px; border:1px solid #ccc; border-radius:6px; }
        .group-title { font-weight: bold; color:#1976d2; margin-bottom:8px }
        pre { margin:0; font-size: 15px; background: #f7f7fc; padding:6px; border-radius:4px;}
        .copy-btn {
            display: inline-block;
            margin-bottom: 8px;
            padding: 4px 16px;
            color: #fff;
            background: #1976d2;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background .2s;
        }
        .copy-btn.copied {
            background: #388e3c;
        }
        .copy-btn.failed {
            background: #ef5350;
        }
    </style>
</head>
<body>
<h2>上传Excel文件，分组展示语言包对象</h2>
<input type="file" id="fileInput" accept=".xlsx, .xls">
<div id="output"></div>

<script>
    document.getElementById("fileInput").addEventListener("change", function(event) {
        const file = event.target.files[0];
        if (!file) return;
        const reader = new FileReader();

        reader.onload = function(e) {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: "array" });
                const worksheet = workbook.Sheets[workbook.SheetNames[0]];
                const jsonData = XLSX.utils.sheet_to_json(worksheet, {defval:""});

                if (!jsonData.length) {
                    document.getElementById("output").innerHTML = `<p>文件为空</p>`;
                    return;
                }

                const columns = Object.keys(jsonData[0]);
                const keyCol = columns[0];
                const langCols = columns.slice(1);
                let html = '';

                langCols.forEach((colName, idx) => {
                    let lines = '';
                    jsonData.forEach(row => {
                        const key = row[keyCol], value = row[colName];
                        if (typeof key === 'string' && key.trim() &&
                            typeof value === 'string' && value.trim()) {
                            const v = String(value).replace(/'/g,"\\'").replace(/\r?\n/g," ").trim();
                            lines += `    '${key}': '${v}',\n`;
                        }
                    });
                    if (lines.trim()) {
                        const codeBlock = `return {\n${lines}}`;
                        html += `
                    <div class="group-block">
                      <div class="group-title">${idx+1}*（${colName}）</div>
                      <button class="copy-btn" data-code="__copy_block${idx}">复制</button>
                      <pre id="__copy_block${idx}">${codeBlock}</pre>
                    </div>`;
                    }
                });

                document.getElementById("output").innerHTML = html;

                // 绑定复制事件
                document.querySelectorAll('.copy-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const preId = btn.getAttribute('data-code');
                        const content = document.getElementById(preId).innerText;

                        // 使用 Clipboard API
                        if (navigator.clipboard && window.isSecureContext) {
                            navigator.clipboard.writeText(content).then(() => {
                                setCopied(btn, true);
                            }, () => {
                                setCopied(btn, false);
                            });
                        } else {
                            // 兼容: 创建textarea
                            const textarea = document.createElement('textarea');
                            textarea.value = content;
                            textarea.style.position = 'fixed';
                            document.body.appendChild(textarea);
                            textarea.focus();
                            textarea.select();
                            try {
                                const success = document.execCommand('copy');
                                setCopied(btn, success);
                            } catch (err) {
                                setCopied(btn, false);
                            }
                            document.body.removeChild(textarea);
                        }
                    });
                });

                function setCopied(btn, success) {
                    if (success) {
                        btn.textContent = "已复制";
                        btn.classList.add("copied");
                    } else {
                        btn.textContent = "复制失败";
                        btn.classList.add("failed");
                    }
                    setTimeout(()=>{
                        btn.textContent = "复制";
                        btn.classList.remove("copied","failed");
                    },1500);
                }
            } catch (error) {
                document.getElementById("output").innerHTML = `<p>处理文件时出错: ${error.message}</p>`;
            }
        };

        reader.readAsArrayBuffer(file);
    });
</script>
</body>
</html>
